package com.emm.yixun.customer.service.impl.app.manage;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.AppPushService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.MessageReceiverService;
import com.emm.yixun.basic.service.NoticeService;
import com.emm.yixun.basic.service.PayDepositService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.SignedService;
import com.emm.yixun.basic.service.SubscribeService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.BusinessAuditReqDto;
import com.emm.yixun.common.app.DistributionConsultantResDto;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.PayDeposit;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.Signed;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.MessageReceiverDto;
import com.emm.yixun.common.model.dto.NoticeDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.IsSendEnum;
import com.emm.yixun.common.utils.MsgUtil;

@Service("businessAuditManage")
public class BusinessAuditManage {

//	private static Logger logger = LoggerFactory.getLogger(BusinessAuditManage.class);
	
	@Autowired
	private PayDepositService payDepositService;
	@Autowired
	private SubscribeService subscribeService;
	@Autowired
	private SignedService signedService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private UserService userService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private CusAppNoticeManage cusAppNoticeManage;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private ProjectRoomService projectRoomService;
	@Autowired
	private MessageReceiverService messageReceiverService;
	@Autowired
	private AppPushService appPushService;
	@Autowired
	private NoticeService noticeService;
	/**
	 * 查询置业顾问列表
	 * @param reqDto
	 * @return
	 */
	public CommonResDTO auditNotice(BusinessAuditReqDto reqDto) {
		DistributionConsultantResDto resDto = new DistributionConsultantResDto();
		try{
			//认筹、认购、签约审核后的提醒消息
			/***
			 * 注:
			 * 	当前只有认筹,认购、签约的审核暂缓 
			 * 
			***/
			User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
			String msgTemp = "你的客户${customer}认筹审核${auditStatus}。";
			String sendMsg = "";
			DictionaryDto dicDto = new DictionaryDto();
			dicDto.setDictionaryValue("NT07");
			Dictionary dic = dictionaryService.selectByDto(dicDto);
			if(dic != null){
				msgTemp = dic.getDictionaryName();
			}
			
			long businessId = Long.parseLong(reqDto.getBusinessId());
			long customerId = 0L;
			long agentId = 0L;
			@SuppressWarnings("unused")
			long roomId = 0L;
			long projectId = 0L;
			//是否无房认筹 0: 有房 1: 无房
			String isPayDeposit = "";
			if("认筹".equals(reqDto.getBusinessType())) {
				PayDeposit pd = payDepositService.selectById(businessId);
				customerId = pd.getCustomerId();
				agentId = pd.getAgentId();
				roomId = pd.getRoomId();
				projectId = pd.getProjectId();
				isPayDeposit = pd.getIsPaydeposit();
			}else if("认购".equals(reqDto.getBusinessType())){
				msgTemp = "你的客户${customer}认购审核${auditStatus}。";
				Subscribe sub = subscribeService.selectById(businessId);
				customerId = sub.getCustomerId();
				roomId = sub.getRoomId();
				agentId = sub.getAgentId();
			}else if("签约".equals(reqDto.getBusinessType())){
				msgTemp = "你的客户${customer}签约审核${auditStatus}。";
				Signed signed = signedService.selectById(businessId);
				customerId = signed.getCustomerId();
				roomId = signed.getRoomId();
				agentId = signed.getAgentId();
			}
			String customerName = "";
			Customer customer = customerService.selectById(customerId);
			if(customer != null){
				customerName = customer.getCustomerName();
				//查询客户所属经纪人
			}
			sendMsg = msgTemp.replace("${customer}", customerName).replace("${auditStatus}", AuditStatusEnum.getByNo(reqDto.getAuditStatus()).getDes());
			
			//创建提醒消息及消息发送人信息
			Map<String, String> noticeParamMap = new HashMap<String, String>();
			noticeParamMap.put("noticeDicId", "115");
			noticeParamMap.put("noticeTempType", "NT07");
			noticeParamMap.put("sendMsg", sendMsg);
			noticeParamMap.put("title", "审核结果");
			noticeParamMap.put("merchantId", String.valueOf(user.getMerchantId()));
			noticeParamMap.put("userCode", user.getUserCode());
			noticeParamMap.put("accessCode", reqDto.getProjectCode());
			noticeParamMap.put("createUserId", String.valueOf(user.getCreateUserId()));
			/*
			 * (ym) 提醒内容增加超链接 start
			 * */
			Map<String,String> replaceValuesMap=new HashMap<String,String>();
			replaceValuesMap.put(MsgUtil.ROOM_ID, "");
			replaceValuesMap.put(MsgUtil.ROOM_NAME, "");
			replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
			replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customer.getCustomerName());
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
	    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
	    	/*
			 * (ym) 提醒内容增加超链接 end
			 * */
			
			List<User> userList = new ArrayList<User>();
			if(agentId != 0){
				userList.add(userService.selectById(agentId));
			}
			CommonResDTO commonResDto = new CommonResDTO();
			String action = "审核结果实时提醒";
			commonResDto = cusAppNoticeManage.createNotice(noticeParamMap, userList, action);
			
			//审核成功
			if(AuditStatusEnum.SUCCESS.getNo().equals(reqDto.getAuditStatus())){
				UserDto userDto = new UserDto();
				userDto.setMerchantId(reqDto.getMerchantId());
				userList = userService.selectListByDto(userDto);
				if("1".equals(commonResDto.getResult())){
					//创建审核结果认筹、认购、签约通知
					//认筹时,要判断是有房还是无房认筹
					if("1".equals(isPayDeposit)){
						//无房认筹
						msgTemp = "无房认筹：${customer}认筹${projectName}项目成功。";
						Project project = projectService.selectById(projectId);
						sendMsg = msgTemp.replace("${customer}", customerName)
								.replace("${projectName}", (project==null?"":project.getProjectName()));
						noticeParamMap.put("noticeTempType", "NT02");
					}else if("0".equals(isPayDeposit)){
						//有房认筹
						msgTemp = "有房认筹: ${customer}认筹房源${roomContent}成功。";
						ProjectRoom projectRoom = projectRoomService.selectById(projectId);
						sendMsg = msgTemp.replace("${customer}", customerName)
								.replace("${roomContent}", (projectRoom==null?"":projectRoom.getCombinedName()));
						noticeParamMap.put("noticeTempType", "NT01");
					}
					noticeParamMap = new HashMap<String, String>();
					noticeParamMap.put("noticeDicId",  dic.getId()+"");
					noticeParamMap.put("sendMsg", sendMsg);
					noticeParamMap.put("title", "审核结果");
					noticeParamMap.put("merchantId", String.valueOf(user.getMerchantId()));
					noticeParamMap.put("userCode", user.getUserCode());
					noticeParamMap.put("accessCode", reqDto.getProjectCode());
					noticeParamMap.put("createUserId", String.valueOf(user.getCreateUserId()));
					commonResDto = cusAppNoticeManage.createNotice(noticeParamMap, userList, action);
				}
			}
			//推送消息给销售组其他成员
			if("1".equals(commonResDto.getResult())){
				//推送消息
				//pushMsg();
			}
		}catch(Exception e){
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("分配职业顾问失败,未知异常!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
	public void pushMsg() throws Exception{
		//1、查询审核结果相关推送消息
		// NT07: 审核结果
		// NT01: 审核结果成功,推送有房认筹、认购、签约通知
		// NT02: 审核结果成功,推送无房认筹、认购、签约通知
		List<MessageReceiverDto> msgRecList = new ArrayList<MessageReceiverDto>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
 		int year = calendar.get(Calendar.YEAR);
 		int month = calendar.get(Calendar.MONTH) + 1;
 		int day = calendar.get(Calendar.DAY_OF_MONTH);
// 		String issueTimeBefore = year + "-" + month + "-" + day + " 00:00:00"; 
 		String issueTimeAfter = year + "-" + month + "-" + day + " 23:59:59"; 
 		//审核结果
 		MessageReceiverDto auditMrDto = new MessageReceiverDto();
 		auditMrDto.setNoticeTempType("NT07");
 		auditMrDto.setIsSend(IsSendEnum.UNSEND.getNo());
 		//loseCusMrDto.setIssueTimeBefore(sdf.parse(issueTimeBefore));
 		//推送所有小于 issueTimeAfter 时间的所有消息
 		auditMrDto.setIssueTimeAfter(sdf.parse(issueTimeAfter));
   	 	List<MessageReceiverDto> auditMrList = messageReceiverService.selectPushMsgListByDto(auditMrDto);
   	 	if(auditMrList != null){
   	 		for(MessageReceiverDto auditMr: auditMrList){
   	 			msgRecList.add(auditMr);
   	 		}
   	 	}
   	 	//有房认筹消息
   	 	MessageReceiverDto withHouseMrDto = new MessageReceiverDto();
   	 	withHouseMrDto.setNoticeTempType("NT01");
   	 	withHouseMrDto.setIsSend(IsSendEnum.UNSEND.getNo());
   	 	//getCusMrDto.setIssueTimeBefore(sdf.parse(issueTimeBefore));
 		//推送所有小于 issueTimeAfter 时间的所有消息
   	 	withHouseMrDto.setIssueTimeAfter(sdf.parse(issueTimeAfter));
   	 	List<MessageReceiverDto> withHouseMrList = messageReceiverService.selectPushMsgListByDto(withHouseMrDto);
   	 	if(withHouseMrList != null){
   	 		for(MessageReceiverDto withHouseMr: withHouseMrList){
   	 			msgRecList.add(withHouseMr);
   	 		}
   	 	}
   	 	
   	 	//无房认筹消息
   	 	MessageReceiverDto noHouseMrDto = new MessageReceiverDto();
   	 	noHouseMrDto.setNoticeTempType("NT01");
   	 	noHouseMrDto.setIsSend(IsSendEnum.UNSEND.getNo());
   	 	//getCusMrDto.setIssueTimeBefore(sdf.parse(issueTimeBefore));
 		//推送所有小于 issueTimeAfter 时间的所有消息
   	 	noHouseMrDto.setIssueTimeAfter(sdf.parse(issueTimeAfter));
   	 	List<MessageReceiverDto> noHouseMrList = messageReceiverService.selectPushMsgListByDto(noHouseMrDto);
   	 	if(noHouseMrList != null){
   	 		for(MessageReceiverDto noHouseMr: noHouseMrList){
   	 			msgRecList.add(noHouseMr);
   	 		}
   	 	}
   	 	
   	 	if(msgRecList != null && msgRecList.size() > 0){
   	 		String noticeIds = "";
   	 		String msgRecIds = "";
   	 		Set<String> noticeIdSet = new HashSet<String>();
   	 		for(MessageReceiverDto msgRecDto: msgRecList){
   	 			//开始推送消息
	   	 		Map<String, String> pushMap = new HashMap<String, String>();
		   	 	pushMap.put("action", "审核结果实时提醒");
		   	 	pushMap.put("remindCategoryId", String.valueOf(msgRecDto.getDictionaryId()));
		   	 	pushMap.put("pushType", msgRecDto.getNoticeTempType());
				String context = msgRecDto.getContent();
				appPushService.pushMessage(String.valueOf(msgRecDto.getReceiverId()), context,
					msgRecDto.getTitle(), pushMap);
				
				//消息ID,Set
				noticeIdSet.add(String.valueOf(msgRecDto.getNoticeId()));
				//消息接收人ID'S
				if(StringUtils.isNotEmpty(msgRecIds)){
					msgRecIds += ",";
				}
				msgRecIds += String.valueOf(msgRecDto.getId());
   	 		}
   	 		//需更新消息ID'S
   	 		if(!noticeIdSet.isEmpty()){
				for(String noticeId: noticeIdSet){
					if(StringUtils.isNotEmpty(noticeIds)){
						noticeIds += ",";
					}
					noticeIds += noticeId;
	   	 		}
   	 		}
   	 		//更新消息
   	 		NoticeDto noticeDto = new NoticeDto();
   	 		noticeDto.setIsSend(IsSendEnum.SEND.getNo());
   	 		noticeService.updates(noticeDto, noticeIds);
   	 		//更新接收人
   	 		MessageReceiverDto updateMRDto = new MessageReceiverDto();
   	 		updateMRDto.setIsSend(IsSendEnum.SEND.getNo());
   	 		messageReceiverService.updates(updateMRDto, msgRecIds);
   	 	}
	}
}
